﻿using System;
using System.Collections.Generic;
using Accona.Remoting.Remoting;

namespace Accona.Remoting
{
    public class RemotingRepository : IRepository
    {
        internal readonly RemoteTranceiver _remoteTranceiver;
        
        public RemotingRepository()
        {
            _remoteTranceiver = new RemoteTranceiver(RemoteExecutionRepository.Instance);
            _remoteTranceiver.SetupCommunication();
        }

        #region IRepository Members

        public T Resolve<T>()
        {            
            object result = RemoteExecutionRepository.Instance.Resolve(typeof (T));
            if (result == null)
                return _remoteTranceiver.Resolve<T>();
            return (T) result;
        }

        #endregion

        public RemotingRepositorySetup Setup()
        {
            var setup = new RemotingRepositorySetup(this);
            return setup;
        }

        internal void Resolve<T>(Func<T> func)
        {
            RemoteExecutionRepository.Instance.AddResolve<T>(func);
            
        }
    }

    public class RemotingRepositorySetup
    {
        internal readonly RemotingRepository _remotingRepository;

        public RemotingRepositorySetup(RemotingRepository remotingRepository)
        {
            _remotingRepository = remotingRepository;
        }

        public RemotingRepositoryResolveSetup<TInterface> Resolve<TInterface>()
        {
            var setup = new RemotingRepositoryResolveSetup<TInterface>(this);
            return setup;
        }
    }

    public class RemotingRepositoryResolveSetup<T>
    {
        private readonly RemotingRepositorySetup _remotingRepositorySetup;

        public RemotingRepositoryResolveSetup(RemotingRepositorySetup remotingRepositorySetup)
        {
            _remotingRepositorySetup = remotingRepositorySetup;
        }

        public void With(Func<T> func)
        {
            _remotingRepositorySetup._remotingRepository.Resolve<T>(func);
        }
    }
}